package top.infopub.mgr.cap.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.dto.cap.ContractGuarantyDto;
import top.infopub.enums.cap.CapProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.cap.dao.ContractGuarantyDao;
import top.infopub.mgr.cap.dao.ContractGuarantyDetailDao;
import top.infopub.mgr.cap.domain.ContractGuarantyDomain;
import top.infopub.mgr.cap.jsonvo.ContractGuarantyJsonVo;
import top.infopub.mgr.cap.service.CapProcessManageService;
import top.infopub.mgr.cap.service.ContractGuarantyService;
import top.infopub.mgr.cap.vo.ContractGuarantyVo;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.model.cap.*;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ContractGuarantyServiceImpl extends GenericServiceImpl<ContractGuaranty, String> implements ContractGuarantyService {


    @Autowired
    private ContractGuarantyDao contractGuarantyDao;
    @Autowired
    private ContractGuarantyDetailDao contractGuarantyDetailDao;
    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;
    @Autowired
    private SetupProService setupProService;
    @Autowired
    private OAFlowService oaFlowService;
    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;
    @Autowired
    private CapProcessManageService capProcessManageService;

    @Override
    public GenericDao<ContractGuaranty, String> getDao() {
        return contractGuarantyDao;
    }

    @Override
    public Page<ContractGuarantyDomain> selectByDomainWhere(Page<ContractGuarantyDomain> page, ContractGuarantyVo contractGuarantyVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<ContractGuarantyDomain>) contractGuarantyDao.selectByDomainWhere(contractGuarantyVo);
    }

    @Override
    public ContractGuarantyJsonVo queryDetailById(String id) {
        ContractGuarantyJsonVo jsonVo = new ContractGuarantyJsonVo();
        String codes = codeGeneratorConfigService.generatorCode("cap_contract_guarantee");
        //如果id为空，基础信息不返回，返回一个项目列表下拉框list
        if(StringUtils.isEmpty(id)){
            /*新增所需要的项目列表下拉框*/
           List<FinancingName> financingNames= contractGuarantyDao.queryListFinancingName();
           for(FinancingName financingName:financingNames){
               //所需要的codes
               financingName.setCodes(codes);
               //查询金融机构下拉框:需要proCode查询,如果不存在id就用上面的项目列表中查询的proCode来查
//               List<ContractGuaranty> institutions= contractGuarantyDao.selectInstitutions(financingName.getProCode());
//               jsonVo.setInstitutions(institutions);
           }
           jsonVo.setFinancingNames(financingNames);

        }else {
            /*融资基本信息*/
            ContractGuarantyDto contractGuarantyDto = contractGuarantyDao.queryDetailById(id);
            jsonVo.setInfo(contractGuarantyDto);

            /*担保单位信息*/
            //如果id为空，子表列表为空，返回空的list
            List<ContractGuarantyDetail> contractGuarantyDetails = contractGuarantyDetailDao.queryListByContractGuaId(contractGuarantyDto.getId());
            jsonVo.setDetails(contractGuarantyDetails);
            for(ContractGuarantyDetail detail:contractGuarantyDetails){
                //查询金融机构下拉框
                List<ContractGuaranty> institutions= contractGuarantyDao.selectInstitutions(contractGuarantyDto.getProCode());
                jsonVo.setInstitutions(institutions);
            }
            /*附件信息表*/
            //附件信息根据详情的procode查询返回
            List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(contractGuarantyDto.getProCode(), ProjectFileTypeEnum.FILE_TYPE49.getCode(), null);
            jsonVo.setFileAtt(setupProService.fileAttaListToArray(projectAttaList));

        }
        //担保单位下拉框必须返回
        /*担保单位公司（下拉框）*/
        List<GuaranteeName> guaranNames = contractGuarantyDetailDao.queryGuaranteeName();
        jsonVo.setGuaranName(guaranNames);

        //枚举类下拉框返回必须-已有
        return jsonVo;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public RspVo edit(String bodyStr,ContractGuarantyDto contractGuarantyDto, List<ContractGuarantyDetail> detailList, List<ProjectAttachment> attachmentList,
                      Integer submitType, AuthorizationVO vo) {
        ContractGuaranty contractGuaranty = new ContractGuaranty();
        BeanUtils.copyProperties(contractGuarantyDto,contractGuaranty);
        if (StringUtils.isNotEmpty(contractGuarantyDto.getId())) {
            //校验数据是否存在
            ContractGuaranty tmpPi = contractGuarantyDao.selectByPrimaryKey(contractGuarantyDto.getId());
            if (tmpPi == null) return RspVo.getFailureResponse(400, "保证合同数据不存在");
            //判断审批状态
            if (org.apache.commons.lang.StringUtils.isNotBlank(tmpPi.getProcessStatus())
                    && (org.apache.commons.lang.StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), tmpPi.getProcessStatus())
                    || org.apache.commons.lang.StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), tmpPi.getProcessStatus()))) {
                return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
            }
            contractGuaranty.setUptBy(vo.getId());
            contractGuaranty.setUptTime(new Date());
            //更新主表信息
            contractGuarantyDao.updateByIdSelective(contractGuaranty);
        }else{
            contractGuaranty.setAddBy(vo.getId());
            contractGuaranty.setAddTime(new Date());
            contractGuarantyDao.insertSelective(contractGuaranty);
        }

        //更新子表数据
        contractGuarantyDetailDao.deleteByPrimaryKey(contractGuaranty.getId());
        if (detailList != null && detailList.size() > 0) {
            for (ContractGuarantyDetail pid : detailList) {
                pid.setCodes(contractGuarantyDto.getCodes());
                pid.setProCode(contractGuaranty.getProCode());
                pid.setAddBy(vo.getCode());
                pid.setAddTime(new Date());
                pid.setContractGuarantyId(contractGuaranty.getId());
            }
            contractGuarantyDetailDao.insertByBatch(detailList);

        }

        //更新附件信息
        projectAttachmentDao.deleteByWhere(contractGuarantyDto.getProCode(), ProjectFileTypeEnum.FILE_TYPE49.getCode(), null);
        if (attachmentList != null && attachmentList.size() > 0) {
            projectAttachmentDao.insertBatch(attachmentList);
        }
        if (submitType == 1) {
            if (org.apache.commons.lang.StringUtils.isNotBlank(contractGuaranty.getOaId())) {
                oaFlowService.finishOA(contractGuaranty.getOaId());
            }
        //由于担保单位和公司数据过多
        ContractGuarantyJsonVo jsonVo=queryDetailById(contractGuaranty.getId());
            List<GuaranteeName> compNames = jsonVo.getGuaranName();
            List<ContractGuarantyDetail> infos = jsonVo.getDetails();
            if (compNames != null && compNames.size() > 0 && infos != null && infos.size() > 0) {
                List<GuaranteeName> tmpList = new ArrayList<>();
                for (ContractGuarantyDetail info : infos) {
                    if (info == null) continue;
                    for (GuaranteeName gn : compNames) {
                        if (gn == null) continue;
                        if (StringUtils.equals(gn.getId(), info.getGuaranteeName())) {
                            tmpList.add(gn);
                            break;
                        }
                    }
                }
                jsonVo.setGuaranName(tmpList);
            } else {
                jsonVo.setGuaranName(null);
            }

            String detailJson= JSON.toJSONString(jsonVo);
            capProcessManageService.sendProcess(CapProcessDetailTypeEnum.PRO_NODE_TYPE10, detailJson, contractGuaranty.getId(), contractGuaranty.getProCode(), vo);
        }
        return RspVo.getSuccessResponse();
    }
}
